<!-- 预约单维护 -->
<template>
  <div class="ky-container">
    <!-- <el-card shadow="hover" class="ky-card ky-card-hdbg title">
      预约单模板维护
    </el-card> -->
    <el-card
      shadow="hover"
      class="ky-card-xs ky-card-hdbg ky-mt10 main-content"
    >
      <el-card shadow="hover" class="ky-card ky-card-hdbg left-main">
        <sde-editor
          ref="sdeEditor"
          @saveModel="saveModel"
          @addNewModel="addNewModel"
          @exportModel="exportModel"
        />
      </el-card>
      <el-card shadow="hover" class="ky-card ky-card-hdbg right-tree">
        <el-select
          size="small"
          v-model="hospitalCode"
          placeholder="请选择"
          @change="hospitalChange"
          filterable
        >
          <el-option
            v-for="(item, index) in mx_hospitalList"
            :key="index"
            :label="item.name"
            :value="item.code"
          ></el-option>
        </el-select>
        <el-tree
          v-loading="loading"
          :data="treeData"
          :props="defaultProps"
          highlight-current
          default-expand-all
          @node-click="handleNodeClick"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>
              <span v-if="(data.patType && !data.children) || data.modalityType">
                【
                <span v-if="data.patType && !data.children">{{data.patType}}</span>
                <span v-if="(data.patType && !data.children) && data.modalityType">·</span>
                <span v-if="data.modalityType">{{data.modalityType}}</span>
                】
              </span>
              {{node.label}}
              <span
                class="default-label"
                v-if="!data.children && data.isDefault"
              >默认</span
              >
            </span>
            <span>
              <el-button
                type="text"
                size="mini"
                class="ky-red-text ky-underline"
                v-if="!data.children && !data.isDefault"
                @click.stop="() => setDefault(node, data)"
              >
                置为默认
              </el-button>
              <el-button
                type="text"
                size="mini"
                class="ky-underline"
                style="margin-left: 0px"
                v-if="!data.children"
                @click="() => changeNode(node, data)"
              >
                编辑
              </el-button>
              <el-button
                type="text"
                size="mini"
                class="ky-underline"
                style="margin-left: 0px"
                v-if="!data.children"
                @click.stop="() => deleteNode(node, data)"
              >
                删除
              </el-button>
            </span>
          </span>
        </el-tree>
      </el-card>
      <save-dialog
        ref="saveDialog"
        :hospital-code="hospitalCode"
        :add-visible.sync="addVisible"
        @save="save"
        :node-data="nodeData"
      ></save-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  reservationList,
  saveServation,
  getReservationObj,
  updateReservation,
  deleteReservation,
  setdefaultReservation
} from '@/api/api.js'
import sdeEditor from './sdeEditor'
import saveDialog from './saveDialog.vue'
export default {
  name: '',
  mixins: [],
  components: { sdeEditor, saveDialog },
  data() {
    return {
      hospitalCode: '',
      loading: false,
      addVisible: false,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      nodeData: {},
      isEdit: false
    }
  },
  watch: {},
  computed: {},
  created() {},
  mounted() {
    this.$getHospitalList()
    this.hospitalCode = this.$store.state.user.hospitalCode
    this.getTreeData()
  },
  methods: {
    handleNodeClick(data) {
      if (data.id) {
        // 向后台发起请求,获得模板，赋值给预约单模板
        this.clickData = data
        getReservationObj({ hospitalCode: this.hospitalCode, id: data.id })
          .then((res) => {
            if (res && res.code === 10000) {
              const htmlData = res.content.templateContent
              this.setHTML(htmlData)
              this.changeMode('DESIGN')
            }
          })
          .catch(() => {})
      }
    },
    saveModel() {
      if (this.clickData) {
        // 编辑
        this.editSave()
        this.isEdit = true
      } else {
        // 新增
        this.addVisible = true
        this.isEdit = false
      }
    },
    exportModel() {
      // 导出模板
      const html = this.getHTML()
      // 定义文件内容，类型必须为Blob 否则createObjectURL会报错
      let content = new Blob([html])
      // 生成url对象
      let urlObject = window.URL || window.webkitURL || window
      let url = urlObject.createObjectURL(content)
      // 生成<a></a>DOM元素
      let el = document.createElement('a')
      // 链接赋值
      el.href = url
      el.download = this.clickData ? this.clickData.label : '预约单模板'
      // 必须点击否则不会下载
      el.click()
      // 移除链接释放资源
      urlObject.revokeObjectURL(url)
    },
    save(data) {
      // 新增保存
      const html = this.getHTML()
      this.setHTML('')
      let params = {
        hospitalCode: this.hospitalCode,
        ...data,
        templateContent: html
      }
      if (!this.isEdit) {
        // 新增
        saveServation(params)
          .then((res) => {
            if (res && res.code === 10000) {
              this.$message.success('模板保存成功')
              this.getTreeData()
            }
          })
          .catch(() => {})
      } else {
        // 编辑保存
        updateReservation(params)
          .then((res) => {
            if (res && res.code === 10000) {
              this.$message.success('修改成功')
              this.getTreeData()
            }
          })
          .catch(() => {})
      }
    },
    editSave() {
      // 编辑保存
      const html = this.getHTML()
      let params = {
        ...this.clickData,
        templateContent: html
      }
      updateReservation(params)
        .then((res) => {
          if (res && res.code === 10000) {
            this.$message.success('修改成功')
          }
        })
        .catch(() => {})
    },
    addNewModel() {
      this.clickData = null
      this.setHTML('')
      this.changeMode('DESIGN')
    },
    setHTML(txthtml) {
      this.$refs.sdeEditor.setHTML(txthtml)
    },
    changeMode(mode) {
      this.$refs.sdeEditor.mode(mode)
    },
    getMode() {
      return this.$refs.sdeEditor.mode()
    },
    getHTML() {
      return this.$refs.sdeEditor.getHTML()
    },
    hospitalChange() {
      this.getTreeData()
      this.clickData = null
      if (this.getMode() !== 'READONLY') {
        this.setHTML('')
      }
    },
    getTreeData() {
      this.loading = true
      reservationList({ hospitalCode: this.hospitalCode })
        .then((res) => {
          this.loading = false
          this.treeData = []
          if (res && res.code === 10000) {
            res.content.list.forEach((el) => {
              let obj = this.treeData.find((td) => {
                return td.dep === el.dep
              })
              if (!obj) {
                let a = {
                  label: el.dep,
                  ...el,
                  children: [{ label: el.templateName, ...el }]
                }
                delete a.modalityType
                this.treeData.push(a)
              } else {
                let a = {
                  label: el.templateName,
                  ...el
                }
                obj.children.push(a)
              }
            })
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    async deleteNode(node, data) {
      //   if (!data.children) {
      let confirmMsg = '此操作将永久删除该模板, 是否继续?'
      this.$confirm(confirmMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteReservation({ hospitalCode: this.hospitalCode, id: data.id })
            .then((res) => {
              if (res && res.code === 10000) {
                const parent = node.parent
                const children = parent.data.children || parent.data
                const index = children.findIndex((d) => d.id === data.id)
                children.splice(index, 1)
                if (this.clickData.id === data.id) {
                  this.setHTML('')
                  this.clickData = null
                }
                this.$message.success('已经成功删除模板')
              }
            })
            .catch(() => {})
        })
        .catch(() => {})
      //   } else {
      //     let successNum = 0
      //     let idArr = data.children.map((e) => { return e.id })
      //     for (const id of idArr) {
      //       await deleteReservation({ id }).then(res => {
      //         if (res && res.code === 10000) {
      //           successNum++
      //           const parent = node.parent
      //           const children = parent.data.children || parent.data
      //           const index = children.findIndex(d => d.id === id)
      //           children.splice(index, 1)
      //           if (this.clickData.id === id) {
      //             this.setHTML('')
      //             this.clickData = null
      //           }
      //         }
      //       }).catch(() => {

      //       })
      //     }
      //     if (successNum > 0) {
      //       this.$message.success(`已经成功删除` + successNum + '个模板')
      //     }
      //   }
    },
    setDefault(node, data) {
      setdefaultReservation({ hospitalCode: this.hospitalCode, id: data.id })
        .then((res) => {
          if (res && res.code === 10000) {
            this.$message.success('成功设置为默认模板')
            this.getTreeData()
          }
        })
        .catch(() => {})
    },
    changeNode(node, data) {
      // 修改模板的名称部门等信息
      this.addVisible = true
      this.nodeData = data
      this.isEdit = true
    }
  },
  beforeDestroy() {},
  destroyed() {},
  beforeUpdate() {},
  updated() {}
}
</script>
<style lang='scss' scoped>
.ky-container {
  height: calc(100vh - 50px);
  .title {
    text-align: center;
    font-size: 20px;
    font-weight: 600;
  }
  .main-content {
    height: 100%;
    /deep/ .el-card__body {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
      height: 100%;
    }
    .left-main {
      width: calc(100% - 410px);
      margin-right: 10px;
      height: 100%;
      .el-card__body {
        height: 100%;
        .sde-root {
          height: 100%;
        }
      }
    }
    .right-tree {
      width: 400px;
      /deep/ .el-card__body {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        height: auto !important;
        .el-tree {
          width: 100%;
        }
      }
    }
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .default-label {
    color: #eee;
    padding: 3px;
    background: #b1b1b1;
    font-size: 12px;
    margin-left: 10px;
  }
}
</style>
